package io.renren.wechat.support;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @author dmcp@qq.com
 * @since 2021/12/21 10:58
 */
public abstract class ServletRequestUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(ServletRequestUtils.class);


    public static void printRequestParameters(HttpServletRequest request) {
        final Enumeration<String> parameterNames = request.getParameterNames();

        String parameterName;
        while (parameterNames.hasMoreElements()) {
            parameterName = parameterNames.nextElement();
            LOGGER.debug("request parameter name: {}, value: {}", parameterName, request.getParameter(parameterName));
        }
    }

    public static void printRequestCookies(HttpServletRequest request) {
        final Cookie[] cookies = request.getCookies();

        if (ArrayUtils.isNotEmpty(cookies)) {
            for (Cookie cookie1 : cookies) {
                LOGGER.debug("request cookie name: {}, value: {}", cookie1.getName(), cookie1.getValue());
            }
        }
    }

    public static String getCookieValue(HttpServletRequest request, String cookieName) {
        final Cookie[] cookies = request.getCookies();

        if (ArrayUtils.isNotEmpty(cookies)) {
            for (Cookie cookie1 : cookies) {
                if (StringUtils.equalsIgnoreCase(cookie1.getName(), cookieName)) {
                    return cookie1.getValue();
                }
                LOGGER.debug("request cookie name: {}, value: {}", cookie1.getName(), cookie1.getValue());
            }
        }

        return null;
    }

    public static Map<String, String> getCookieValueAsMap(HttpServletRequest request) {
        final Cookie[] cookies = request.getCookies();

        if (ArrayUtils.isNotEmpty(cookies)) {
            Map<String, String> cookieMap = new HashMap<>();
            for (Cookie cookie1 : cookies) {
                cookieMap.put(cookie1.getName(), cookie1.getValue());
            }

            LOGGER.debug("request cookieMap: {}", cookieMap);
            return cookieMap;
        }

        return Collections.emptyMap();
    }
}
